package com.download.web.api;

import com.alibaba.fastjson.JSONObject;
import com.download.util.HttpUtil;
import com.download.web.entity.SysThirdAccount;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * @description: 调用第三方api
 * @author: cmy
 * @create: 2019-03-01 18:33
 **/
@Service
public class ApiRequestService {

    @Autowired
    private RestTemplate restTemplate;

//    1	101500916	http://www.thisding.com/oauth/callback/qq	18
//            2	1327828830	http://www.thisding.com/oauth/callback/weibo	17
//
    //微博获取token
    public Map<String, Object> userToken(String code, SysThirdAccount sysThirdAccount){
        Map<String,String> requestMap=new HashMap<>();
        requestMap.put("client_id",sysThirdAccount.getAppid());
        requestMap.put("client_secret",sysThirdAccount.getClientSecret());
        requestMap.put("redirect_uri",sysThirdAccount.getRedirectUri());
        requestMap.put("grant_type","authorization_code");
        requestMap.put("code",code);
//        WeiboTokenRequest request=new WeiboTokenRequest(sysThirdAccount.getAppid(),sysThirdAccount.getClientSecret(),sysThirdAccount.getRedirectUri(),"authorization_code",code);
//        String responseMap= restTemplate.postForObject(WeiboAPI.accessToken,requestMap,String.class);
        String doPost=HttpUtil.sendPost(WeiboAPI.accessToken,requestMap);
        Map<String, Object> responseMap=JSONObject.parseObject(doPost,Map.class);
        return responseMap;
    }
//     return WeiboAPI.accessToken;
//}else if(type.equals("18")){
//        //如果是qq登录返回qq获取token地址
//        return QQAPI.token;
    //微博获取token
    public Map<String, Object> qquserToken(String code, SysThirdAccount sysThirdAccount){
        Map<String,String> requestMap=new HashMap<>();
        requestMap.put("client_id",sysThirdAccount.getAppid());
        requestMap.put("client_secret",sysThirdAccount.getClientSecret());
        requestMap.put("redirect_uri",sysThirdAccount.getRedirectUri());
        requestMap.put("grant_type","authorization_code");
        requestMap.put("code",code);

        String url=String.format(QQAPI.token,"authorization_code",sysThirdAccount.getAppid(),sysThirdAccount.getClientSecret(),code,sysThirdAccount.getRedirectUri());
        //token?grant_type=%s&client_id=%s&client_secret=%s&code=%s&redirect_uri=%s
        String tokenStr =restTemplate.getForObject(url,String.class);
        String[] tokenArr=tokenStr.split("&");
        Map<String, Object> responseMap=new HashMap<>();
        for (int i=0;i<tokenArr.length;i++){
            String[] tArr=tokenArr[i].split("=");
            responseMap.put(tArr[0],tArr[1]);
        }
//        Map<String, Object> responseMap=JSONObject.parseObject(doPost,Map.class);
        return responseMap;
    }

    public Map<String,Object> weiboUserInfo(String accessToken,String userId){
        /*Map<String,Object> requestMap=new HashMap<>();
        requestMap.put("access_token",accessToken);*/
//        Map<String,Object> responseMap= restTemplate.getForObject(WeiboAPI.userInfo,Map.class,accessToken);
        String getData=HttpUtil.get(String.format(WeiboAPI.userInfo, accessToken,userId));
        Map<String, Object> responseMap=JSONObject.parseObject(getData,Map.class);
        return responseMap;
    }

    public Map<String,Object> qqUserOpenId(String accessToken){
        String getData=restTemplate.getForObject(String.format(QQAPI.qqOpenId, accessToken),String.class);
//        String getData=HttpUtil.get(String.format(QQAPI.qqOpenId, accessToken));
        Map<String, Object> responseMap=JSONObject.parseObject(getData.substring(10,getData.length()-4),Map.class);
        return responseMap;
    }
    //access_token	可通过使用Authorization_Code获取Access_Token 或来获取。
    //access_token有3个月有效期。
    //oauth_consumer_key	申请QQ登录成功后，分配给应用的appid
    //openid
    public Map<String,Object> qqUserInfo(String accessToken,String oauthConsumerKey, String openId){
        /*Map<String,Object> requestMap=new HashMap<>();
        requestMap.put("access_token",accessToken);*/
//        Map<String,Object> responseMap= restTemplate.getForObject(WeiboAPI.userInfo,Map.class,accessToken);
        String getData=HttpUtil.get(String.format(QQAPI.qqUserInfo, oauthConsumerKey, accessToken,openId));
        Map<String, Object> responseMap=JSONObject.parseObject(getData,Map.class);
        return responseMap;
    }


    private String loginType(String type){

        if(type.equals("17")){
            //如果是微博登录返回微博获取token地址
            return WeiboAPI.accessToken;
        }else if(type.equals("18")){
            //如果是qq登录返回qq获取token地址
            return QQAPI.token;
        }
        return null;
    }




    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }


}
